package cn.dckeji.dcssm.controller;


import cn.dckeji.dcssm.common.model.ResultModel;
import cn.dckeji.dcssm.common.utils.ExcelUtils;
import cn.dckeji.dcssm.common.utils.FileUtil;
import cn.dckeji.dcssm.common.utils.MD5Util;
import cn.dckeji.dcssm.common.utils.QiNiuUpLode;
import cn.dckeji.dcssm.entity.Admin;
import cn.dckeji.dcssm.entity.Park;
import cn.dckeji.dcssm.entity.Role;
import cn.dckeji.dcssm.entity.Users;
import cn.dckeji.dcssm.service.UsersService;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Kenny
 * @since 2019-07-31
 */
@RestController
@RequestMapping("/users")
public class UsersController {


    @Autowired
    private UsersService usersService;

    /**
     * 分页查询管理员
     * @param pageNumber
     * @param pageSize
     * @param
     * @return
     */
    @GetMapping("/page")
    public JSONObject page(Integer pageNumber, Integer pageSize, @RequestParam(value = "userPhone",required = false) String userPhone,@RequestParam(value = "userName",required = false) String userName) {
        QueryWrapper<Users> adminQueryWrapper = new QueryWrapper<>();
        adminQueryWrapper.orderByDesc("gmt_create");
        if (StringUtils.isNotBlank(userPhone)) {
            adminQueryWrapper.like("userPhone", userPhone);
        }
        if (StringUtils.isNotBlank(userName)) {
            adminQueryWrapper.like("userName", userName);
        }
        IPage<Users> page = usersService.page(new Page<>(pageNumber, pageSize), adminQueryWrapper);
        List<Users> records = page.getRecords();
/*        List<Map> adminMapList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(records)) {
            for (Admin admin:records) {
                Map<String, Object> stringObjectMap = BeanUtil.beanToMap(admin);
                String roleId = admin.getRoleId();
                Role role = roleService.getById(roleId);
                String roleName = role.getRoleName();
                stringObjectMap.put("roleName", roleName);
                adminMapList.add(stringObjectMap);
            }
        }*/
        return ResultModel.page(page.getTotal(),  page.getRecords());
    }

    /**
     * 保存管理员
     * @param
     * @return
     */
    @PostMapping("/saveUsers")
    public ResultModel<Object> saveUsers(Users users) {
        boolean b = usersService.saveUsers(users);
        if (b) {
            return ResultModel.success();
        }else {
            return ResultModel.failure("手机号已存在,请更换重试");
        }
    }

    /**
     * 删除管理员
     * @param
     * @return
     */
    @PostMapping("/deleteById")
    public ResultModel<Object> deleteById(String userId) {
        usersService.removeById(userId);
        return ResultModel.success();
    }


    /**
     * 重置管理员密码
     * @param
     * @return
     */
    @PostMapping("/restPassword")
    public ResultModel<Object> restPassword(String userId) {
        usersService.updateAdminPassword(userId);
        return ResultModel.success();
    }


    @ResponseBody
    @RequestMapping(value = "importData")
    public ResultModel importData(@RequestParam("file") MultipartFile[] file, HttpServletRequest request) throws IOException {
        ResultModel jsonObject = QiNiuUpLode.uploadFile(file, request,"file-excel","",false);
        List<Map> lists = (List<Map>) jsonObject.getData();
        Map map = lists.get(0);
        String string = (String) map.get("filePath");
        List<Users> studyList = ExcelUtils.readExcelToSql(string);
        FileUtil.deleteFolder(string,true);
        if(studyList.size()<=0){
            return ResultModel.failure("不能导入空的文件");
        }
        //  EHCacheUtils cache = EHCacheUtils.getInstance();
        // cache.put("progress","progress",0);
        int count = 0;
        int size = studyList.size();
        for (int i = 0 ; i<studyList.size(); i++){
            Users study = studyList.get(i);
            Users users1 = usersService.getOne(new QueryWrapper<Users>().eq("userPhone", study.getUserPhone()).eq("is_deleted",0));
            if(null!=users1){
                continue;
            }
            String userPwd = study.getUserPwd();
            if(StringUtils.isBlank(userPwd)){
                String s = MD5Util.MD5Encode("123456", "utf-8");
                study.setUserPwd(s);
            }else{
                String s = MD5Util.MD5Encode(userPwd, "utf-8");
                study.setUserPwd(s);
            }
            usersService.save(study);
            //  double  my_progress = (count / (double)size)*100;
            //  if(my_progress>99){
            //       my_progress=100;
            //   }
            //  cache.put("progress","progress",  String.valueOf((new Double(my_progress)).intValue()));
            ++count;
        }
        return ResultModel.success("成功导入"+studyList.size()+"条信息");
    }

}

